package com.gylang.print.richtext.processor;

import cn.hutool.core.collection.CollUtil;
import com.gylang.print.richtext.RichHelper;
import com.gylang.print.richtext.append.IRichAppend;
import com.gylang.print.richtext.resolver.StyleResolver;
import com.gylang.print.richtext.component.BaseRichList;
import com.gylang.print.richtext.component.BaseRich;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 文本占位替换
 *
 * @author gylang
 * data 2021/7/8
 */
public class ListProcessor implements IRichAppend, StyleResolver {


	private static final Set<String> UL_TAG = new HashSet<>();

	static {
		UL_TAG.add("ul");
		UL_TAG.add("ol");
	}

	@Override
	public Element append(Element element, Map<String, Object> data) {

		// 获取占位符
		String tagName = element.tagName();
		if (isUlTag(tagName)) {
			replaceAll(data, element);
		}
		// 获取每一行数据
		Elements elements = element.select("li");
		// 占位替换
		if (CollUtil.isEmpty(elements)) {
			return element;
		}
		// 判断是否存在占位情况
		for (Element tr : elements) {
			// 正则获取所有的占位替换属性
			replaceAll(data, tr);
		}
		return element;
	}

	private boolean isUlTag(String tagName) {

		return UL_TAG.contains(tagName);
	}

	@Override
	public boolean resolve(Element element, List<BaseRich> component, BaseRich parent) {

		if (!isUlTag(element.tagName())) {
			return false;
		}
		// 解析表格数据
		// 获取每一行数据
		Elements elements = element.select("li");

		// 判断是否存在占位情况
		BaseRichList richList = new BaseRichList();
		richList.copyStyle(parent);
		for (Element tr : elements) {

			// 解析文本样式
			List<BaseRich> baseRiches = RichHelper.style(tr);
			if (CollUtil.isNotEmpty(baseRiches)) {
				richList.setRow(baseRiches);
			}
			component.add(richList);
		}
		return true;
	}
}
